package ldh.im.fxbase.util;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.opencv.opencv_videoio.VideoCapture;

import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Mixer;

public class AudioUtil {

    private static int spikesensitivity = 50;
    private static int sens = 7;
    private static byte smoothedValue = 0;
    private static int smoothing = 2;

    public static byte[] removeNoise(byte[] b, int length) {
        byte[] returnThis = new byte[b.length];
        for( int i = 0; i < length; i++){
            smoothedValue += (b[i] - smoothedValue) / smoothing;
            returnThis[i] = smoothedValue;
        }
        return returnThis;
    }

    /**
     * 检查是否有摄像头，能够支持视频聊天
     * @return
     */
    public static boolean checkHaveCamera() {
        try {
            VideoCapture capture = new VideoCapture(0);
            if (capture.isOpened()) {
                capture.release();
                return true;
            }
        } catch (Exception e) {
        }
        return false;
    }

    /**
     * 检查是否有麦克风，是否支持语音聊天
     * @return
     */
    public static boolean checkHaveMicrophone(){
        boolean hasMicrophone = false;
        Mixer.Info[] mixerInfos = AudioSystem.getMixerInfo();
        for (Mixer.Info info : mixerInfos) {
            Mixer mixer = AudioSystem.getMixer(info);
            if (mixer.getTargetLineInfo().length > 0) {
                hasMicrophone = true;
                break;
            }
        }
        return hasMicrophone;
    }

    public static int calcAudioTime(String audioPath) {
        try {
            FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(audioPath);
            grabber.start();
            long time = grabber.getLengthInTime();
            return (int) (time/1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
